<template>
  <div class="conversation-history">
    <div class="history-header">
      <h3>对话历史</h3>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索对话..."
          size="small"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterType" placeholder="类型筛选" size="small" clearable>
          <el-option label="全部" value="" />
          <el-option label="数学" value="数学" />
          <el-option label="物理" value="物理" />
          <el-option label="化学" value="化学" />
          <el-option label="编程" value="编程" />
          <el-option label="图像识别" value="图像识别" />
          <el-option label="其他" value="其他" />
        </el-select>
        <el-button size="small" @click="clearAllHistory" type="danger" plain>
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
      </div>
    </div>

    <div class="history-list">
      <div v-if="filteredHistory.length === 0" class="empty-state">
        <el-icon><ChatDotRound /></el-icon>
        <p>暂无对话历史</p>
      </div>
      
      <div
        v-for="conversation in filteredHistory"
        :key="conversation.id"
        class="history-item"
        @click="loadConversation(conversation)"
      >
        <div class="item-header">
          <div class="question-preview">
            <el-icon v-if="conversation.imageUrl" class="image-icon"><Picture /></el-icon>
            <span class="question-text">{{ conversation.question.substring(0, 50) }}{{ conversation.question.length > 50 ? '...' : '' }}</span>
          </div>
          <div class="item-actions">
            <el-button
              size="small"
              type="text"
              @click.stop="copyConversation(conversation)"
              title="复制"
            >
              <el-icon><CopyDocument /></el-icon>
            </el-button>
            <el-button
              size="small"
              type="text"
              @click.stop="deleteConversation(conversation.id)"
              title="删除"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        
        <div class="item-meta">
          <el-tag v-if="conversation.questionType" size="small" type="info">
            {{ conversation.questionType }}
          </el-tag>
          <span class="timestamp">{{ formatTime(conversation.timestamp) }}</span>
        </div>
        
        <div class="answer-preview">
          {{ conversation.answer.substring(0, 100) }}{{ conversation.answer.length > 100 ? '...' : '' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Delete, CopyDocument, ChatDotRound, Picture } from '@element-plus/icons-vue'
import { useAiSolverStore, type ConversationHistory } from '@/store/ai-solver'

const aiSolverStore = useAiSolverStore()

const searchQuery = ref('')
const filterType = ref('')

// 筛选后的历史记录
const filteredHistory = computed(() => {
  let history = aiSolverStore.conversationHistory
  
  // 按类型筛选
  if (filterType.value) {
    history = aiSolverStore.filterByType(filterType.value)
  }
  
  // 按搜索词筛选
  if (searchQuery.value) {
    history = aiSolverStore.searchHistory(searchQuery.value)
  }
  
  return history
})

// 加载对话
const loadConversation = (conversation: ConversationHistory) => {
  // 触发父组件事件
  emit('load-conversation', conversation)
}

// 复制对话
const copyConversation = async (conversation: ConversationHistory) => {
  const text = `问题：${conversation.question}\n\n答案：${conversation.answer}`
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('对话已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 删除对话
const deleteConversation = (id: string) => {
  aiSolverStore.removeConversation(id)
  ElMessage.success('对话已删除')
}

// 清空所有历史
const clearAllHistory = () => {
  aiSolverStore.clearHistory()
  ElMessage.success('历史记录已清空')
}

// 格式化时间
const formatTime = (time: Date) => {
  const now = new Date()
  const diff = now.getTime() - time.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return time.toLocaleDateString('zh-CN')
  }
}

// 定义事件
const emit = defineEmits<{
  'load-conversation': [conversation: ConversationHistory]
}>()
</script>

<style lang="scss" scoped>
.conversation-history {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  background: #f8f9fa;

  h3 {
    margin: 0 0 12px 0;
    font-size: 16px;
    color: #333;
  }

  .header-actions {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;

    .search-input {
      flex: 1;
      min-width: 200px;
    }
  }
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
  color: #999;

  .el-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

.history-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #f8f9fa;
  }

  &:last-child {
    border-bottom: none;
  }

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;

    .question-preview {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 6px;

      .image-icon {
        color: #1890ff;
        font-size: 14px;
      }

      .question-text {
        font-size: 14px;
        color: #333;
        line-height: 1.4;
      }
    }

    .item-actions {
      display: flex;
      gap: 4px;
      opacity: 0;
      transition: opacity 0.2s;
    }
  }

  &:hover .item-actions {
    opacity: 1;
  }

  .item-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;

    .timestamp {
      font-size: 12px;
      color: #999;
    }
  }

  .answer-preview {
    font-size: 13px;
    color: #666;
    line-height: 1.4;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .history-header .header-actions {
    flex-direction: column;
    align-items: stretch;

    .search-input {
      min-width: auto;
    }
  }
}
</style>
